module(...,package.seeall)
	
	local storyboard = require( "storyboard" )
	local scene = storyboard.newScene()
	local ui = require ("ui")
	local wEasing = require "wEasing"
	local gui = require "Stage3.Stage3HomeGui".new()
	local score = 0
function scene:createScene(event)
	local group = self.view
end
-- Called immediately after scene has moved onscreen:
function scene:enterScene( event )
	local mainHomeGroup = self.view
	local arrayInsect = {}
	local timer_countdown
	local delay = 100
	local time1 = 20000
	local changeTime = 60
	local deltaScore = 0
	local timeReady = 1
	local btnLeft
	local btnRight
	local loop = 0
	local i  = 0
	local var = math.random(1,16)
	local arrayStar = {}
	local countInsect = 0
	local keyLock = false
	local numberStar = 0
	local bg
	local txtScore
	local txtTimePlay
	local txtTimeReady
	local toothBrush
	local btnPause
	local dt--thoi gian xuat hien mot vet ban
	local arrayScore = {20,25,30,35,40}
	local timefinish
	--------------------------function----------------------------
	--------------------------------------------------------------
	onStartPopupPause = function()
		if(timer_countdown ~= nil)then
			--timeFormer = system.getTimer()
			timer.pause(timer_countdown)
		end
		Runtime:removeEventListener("enterFrame", changeInsect)
		btnLeft:removeEventListener("touch",onClick)
		btnRight:removeEventListener("touch",onClick)
	end
	onResumePopup = function()
		if(timer_countdown ~= nil)then
			timer.resume(timer_countdown)
		end
		Runtime:addEventListener("enterFrame", changeInsect)
		btnLeft:addEventListener("touch",onClick)
		btnRight:addEventListener("touch",onClick)
	end
	function finishedGame()
		if score <20 then
			numberStar = 0
		elseif score >= 20 and score < 25 then -- 1 sao
			numberStar = 1
		elseif score >= 25 and score < 30 then -- 2 sao
			numberStar = 2
		elseif score >= 30 and score < 35 then -- 3 sao
			numberStar = 3
		elseif score >= 35 and score < 40 then -- 4 sao
			numberStar = 4
		else -- 5 sao
			numberStar = 5
		end
		local g1
			g1 = require "popup.popupWin".new(score,numberStar,arrayScore,onReplayButtonTap)
		transition.to(g1,{time = 200,alpha = 1, x = 0, y = 0, transition = wEasing.easeOutElastic})
	end
	function Pause()
		local g1 = require "popup.popupPause".new(onResumePopup,onReplayButtonTap)
			local group1 = display.newGroup()
			group1:insert(g1)
			mainHomeGroup:insert(group1)
			group1.y = -300
			transition.to(group1,{time = 200,alpha = 1, x = 0, y = 0, transition = wEasing.easeOutElastic, onStart = onStartPopupPause})
		
	end
	function randomInsect()
		var2 = toothBrush.x
		var = math.random(1,16)
		if toothBrush.x == 120 then
			while (var>=1 and var<=3) or (var>=8 and var<=11) do
				var = math.random(1,16)
			end
		end
		if toothBrush.x == 152 then
			while (var>= 1 and var <=4) or (var >=9 and var <=12) do
				var = math.random(1,16)
			end
		end
		if toothBrush.x == 184 then
			while (var>=2 and var<=5) or (var>=10 and var<=13) do
				var = math.random(1,16)
			end
		end
		if toothBrush.x == 216 then
			while (var >=3 and var<=6) or (var>=11 and var<=14) do
				var = math.random(1,16)
			end
		end
		if toothBrush.x == 248 then
			while (var>=4 and var<=7) or (var>=12 and var<=15) do
				var = math.random(1,16)
			end
		end
		if toothBrush.x == 280 then
			while (var>=5 and var<=8) or (var>=13 and var<=16) do
				var = math.random(1,16)
			end
		end
		if toothBrush.x == 312 then
			while (var>=6 and var<=8) or (var>=14 and var<= 16) do
				var = math.random(1,16)
			end
		end
		for i = 1,16 do
			if i == var then
				arrayInsect[i].isVisible = true
				--check(toothBrush.x)
			end
			if i ~= var then
				arrayInsect[i].isVisible = false
			end
		end
	end
	--------------ham kiem tra an diem-------------
	function check(a)
		if keyLock == false then
			if a == 120 then
				if arrayInsect[1].isVisible == true or arrayInsect[2].isVisible == true
					or arrayInsect[9].isVisible == true or arrayInsect[10].isVisible == true then
						score = score+1
						countInsect = 0
				end
			elseif a == 152 then 
				if arrayInsect[2].isVisible == true or arrayInsect[3].isVisible == true 
					or arrayInsect[10].isVisible == true or arrayInsect[11].isVisible == true then
						score = score+1
						countInsect = 0
				end
			elseif a == 184 then
				if arrayInsect[3].isVisible == true or arrayInsect[4].isVisible == true 
					or arrayInsect[11].isVisible == true or arrayInsect[12].isVisible == true then
						score = score+1
						countInsect = 0
				end
			elseif a ==216 then 
				if arrayInsect[4].isVisible == true or arrayInsect[5].isVisible == true 
					or arrayInsect[12].isVisible == true or arrayInsect[13].isVisible == true then
						score = score +1
						countInsect = 0
				end
			elseif a == 248 then
				if arrayInsect[5].isVisible == true or arrayInsect[6].isVisible == true 
					or arrayInsect[13].isVisible == true or arrayInsect[14].isVisible == true then
						score = score+1
						countInsect = 0
				end
			elseif a == 280 then
				if arrayInsect[6].isVisible == true or arrayInsect[7].isVisible == true
					or arrayInsect[14].isVisible == true or arrayInsect[15].isVisible == true then
						score = score + 1
						countInsect = 0
				end
			else 
				if arrayInsect[7].isVisible == true or arrayInsect[8].isVisible == true 
					or arrayInsect[15].isVisible == true or arrayInsect[16].isVisible == true then
						score = score + 1
						countInsect = 0
				end
			end
			txtScore.text = score.." PTS"
		end
	end

	function playAgain()
		
	end
---------------- danh gia sao cho nguoi choi----------------
	function onReplayButtonTap()
		if(timer_countdownReady ~= nil)then
			timer.cancel(timer_countdownReady)
		end
		Init()
	end
	function checkWin()
		if score <20 then
			numberStar = 0
		elseif score >= 20 and score < 25 then -- 1 sao
			numberStar = 1
		elseif score >= 25 and score < 30 then -- 2 sao
			numberStar = 2
		elseif score >= 30 and score < 35 then -- 3 sao
			numberStar = 3
		elseif score >= 35 and score < 40 then -- 4 sao
			numberStar = 4
		else -- 5 sao
			numberStar = 5
		end
	end
	function Init()
		score = 0
		timeReady = 1
		time1 = 20000
		changeTime = 2000
		numberStar = 0
		countInsect = 0
		txtTimeReady.alpha = 1
		txtTimeReady.text = 3
		txtTimePlay.alpha = 0
		txtTimePlay.text = 20
		toothBrush.alpha = 0
		txtScore.alpha = 0
		btnLeft.alpha = 0
		btnRight.alpha = 0
		btnPause.alpha = 0
		keyLock = false
		for i = 1,16 do
			arrayInsect[i].isVisible = false
		end
		toothBrush.x = gui.toothBrush.x
		timer_countdownReady = timer.performWithDelay(1000,countdownReady,0)
	end
	-----------------------------------------------
	deltaTime = changeTime
	function changeInsect()
		i = i+1
		
		if countInsect == 0 then
			randomInsect()
			countInsect = 1
			return
		end
		if i == deltaTime then
			score = score-deltaScore
			txtScore.text = score.." PTS"
			i = 0
			randomInsect()
		end 
	end
	function onClick(event)
		phase = event.phase
		if (phase == "began") then
			local t = event.target
				if(t.id == "left") then
					toothBrush.x = toothBrush.x -32 
					if toothBrush.x >= 120 then
						check(toothBrush.x)
					else
						timer.cancel(timer_countdown)
						keyLock = true
						btnLeft:removeEventListener("touch",onClick)
						btnRight:removeEventListener("touch",onClick)
						Runtime:removeEventListener("enterFrame", changeInsect)
						timefinish = timer.performWithDelay(300,function()
																	finishedGame()
																end ,1)	
						
					end
				end
				if (t.id == "right") then
					toothBrush.x = toothBrush.x +32
					if toothBrush.x <= 312 then
						check(toothBrush.x)
					else 
						timer.cancel(timer_countdown)
						keyLock = true
						btnLeft.isVisible = false
						btnRight.isVisible = false
						Runtime:removeEventListener("enterFrame", changeInsect)
						timefinish = timer.performWithDelay(300,function()
																	finishedGame()
																end ,1)
					end
				end
			end
		end
	function manageTotalTime()
			time1 = time1-100
			txtTimePlay.text = (math.round((time1)/100))/10 ..""
		if time1>15000 then
			deltaTime = changeTime	
		end
		if time1>10000 and time1<=15000 then
			deltaTime = changeTime*1
		end
		if time1>5000 and time1<= 10000 then
			deltaTime = changeTime*1
		end
		if time1<=5000 then
			deltaTime = changeTime *1
		end
		if(time1<0) then
			  txtTimePlay.text = "0"
			  timer.cancel(timer_countdown)
			  keyLock = true
			  btnLeft:removeEventListener("touch", onClick)
			  btnRight:removeEventListener("touch", onClick)
			  Runtime:removeEventListener("enterFrame", changeInsect)
			  timefinish = timer.performWithDelay(300,function()
																	finishedGame()
																end ,1)
		end
		 
	end
	
	function countdownReady ()
		score = 0
		txtScore.text = score
		timeReady = timeReady - 1
			txtTimeReady.text = timeReady
			-- if txtTimeReady ~= nil and statusBoard== "start" then
				-- txtTimeReady.alpha = 1
			-- end
		if timeReady <1 then
			txtTimeReady.alpha = 0
			go.alpha = 1
		end
		if timeReady <-1 then
			txtTimeReady.alpha = 0
			go.alpha = 0
			timer.cancel(timer_countdownReady)
			txtTimePlay.alpha = 1
			toothBrush.alpha = 1
			btnPause.alpha = 1
			btnLeft.alpha = 1
			btnRight.alpha = 1
			txtScore.alpha = 1
			txtTimePlay.alpha = 1
			timer_countdown = timer.performWithDelay(delay, manageTotalTime, loop)
			Runtime:addEventListener("enterFrame",changeInsect)
			btnLeft:addEventListener("touch",onClick)
			btnRight:addEventListener("touch", onClick)
		end
	end
	
	bg = display.newImageRect(mainHomeGroup,gui.bg.fn, gui.bg.w, gui.bg.h)
		bg.x = gui.bg.x
		bg.y = gui.bg.y
	txtTimeReady = display.newText(mainHomeGroup, timeReady,gui.txtTimeReady.x -20, gui.txtTimeReady.y, gui.txtTimeReady.font, gui.txtTimeReady.size)
			txtTimeReady:setTextColor(unpack(gui.txtTimeReady.color))
			txtTimeReady.alpha = 0
	toothBrush = display.newImageRect(mainHomeGroup,gui.toothBrush.fn, gui.toothBrush.w, gui.toothBrush.h)
		toothBrush.x = gui.toothBrush.x
		toothBrush.y = gui.toothBrush.y
		toothBrush.alpha = 0
	go = display.newImageRect(mainHomeGroup, gui.go.fn, gui.go.w, gui.go.h)
		go.x = gui.go.x
		go.y = gui.go.y
		go.alpha = 0
	
	a = 0
	for i = 1, 8 do
		arrayInsect[i] = display.newImageRect(mainHomeGroup, gui.insect.fn, gui.insect.w, gui.insect.h)
			arrayInsect[i].x = gui.insect.x+a
			arrayInsect[i].y = gui.insect.y
			a = a+32
			arrayInsect[i].isVisible = false
		mainHomeGroup:insert(arrayInsect[i])
	end
	a= 0
	for i = 9,16 do
		arrayInsect[i] = display.newImageRect(mainHomeGroup, gui.insect.fn, gui.insect.w, gui.insect.h)
			arrayInsect[i].x = gui.insect.x+a
			arrayInsect[i].y = gui.insect.y+50
			a = a+32
			arrayInsect[i].isVisible = false
		mainHomeGroup:insert(arrayInsect[i])
	end
	txtScore = display.newText(mainHomeGroup,score.." PTS",gui.txtScore.x, gui.txtScore.y, gui.txtScore.font, gui.txtScore.size)
		txtScore:setTextColor(unpack(gui.txtScore.color))
		txtScore.alpha = 0
	txtTimePlay = display.newText(mainHomeGroup,time1/1000,gui.txtTimer.x, gui.txtTimer.y,native.systemFont, gui.txtTimer.size)
		txtTimePlay:setTextColor(unpack(gui.txtTimer.color))
		mainHomeGroup:insert(txtTimePlay)
		txtTimePlay.alpha = 0
	btnPause = ui.newButton({ defaultSrc = gui.btnPause.fn,
											overSrc = gui.btnPause.fn,
											defaultX = gui.btnPause.w,
											defaultY = gui.btnPause.h,
											overX = gui.btnPause.w,
											overY = gui.btnPause.h,
											overAlpha = gui.btnPause.overAlpha,
											overScale = gui.btnPause.overScale,
											x = gui.btnPause.x,
											y = gui.btnPause.y,
											onRelease = Pause
										})
		mainHomeGroup:insert(btnPause)
		btnPause.alpha = 1
		btnLeft = display.newImageRect(mainHomeGroup,gui.btnLeft.fn,gui.btnLeft.w, gui.btnLeft.h)
			btnLeft.x = gui.btnLeft.x
			btnLeft.y = gui.btnLeft.y
			btnLeft.id = "left"
			btnLeft.alpha = 0
		btnRight = display.newImageRect(mainHomeGroup,gui.btnRight.fn,gui.btnRight.w, gui.btnRight.h)
			btnRight.x = gui.btnRight.x
			btnRight.y = gui.btnRight.y
			btnRight.id = "right"
			btnRight.alpha = 0
	timer_countdownReady = timer.performWithDelay(1000,countdownReady,0)
	return mainHomeGroup
end


-- Called when scene is about to move offscreen:
function scene:exitScene( event )
	local group = self.view
	
	-----------------------------------------------------------------------------
	
	--	INSERT code here (e.g. stop timers, remove listeners, unload sounds, etc.)
	
	-----------------------------------------------------------------------------
	
end


-- Called prior to the removal of scene's "view" (display group)
function scene:destroyScene( event )
	local group = self.view
	
	-----------------------------------------------------------------------------
	
	--	INSERT code here (e.g. remove listeners, widgets, save state, etc.)
	
	-----------------------------------------------------------------------------
	
end

---------------------------------------------------------------------------------
-- END OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------

-- "createScene" event is dispatched if scene's view does not exist
scene:addEventListener( "createScene", scene )

-- "enterScene" event is dispatched whenever scene transition has finished
scene:addEventListener( "enterScene", scene )

-- "exitScene" event is dispatched before next scene's transition begins
scene:addEventListener( "exitScene", scene )

-- "destroyScene" event is dispatched before view is unloaded, which can be
-- automatically unloaded in low memory situations, or explicitly via a call to
-- storyboard.purgeScene() or storyboard.removeScene().
scene:addEventListener( "destroyScene", scene )

---------------------------------------------------------------------------------

return scene
